package com.ydkfjs.service.impl;

import cn.dev33.satoken.secure.BCrypt;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ydkfjs.common.Result;
import com.ydkfjs.constants.LoginConstant;
import com.ydkfjs.constants.UserConstants;
import com.ydkfjs.model.dto.UserRegisterRequest;
import com.ydkfjs.model.po.User;
import com.ydkfjs.service.UserService;
import com.ydkfjs.mapper.UserMapper;
import com.ydkfjs.utils.HBAssert;
import com.ydkfjs.utils.IpUtils;
import com.ydkfjs.utils.RedisCacheUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;

/**
 * @author hb
 * @description 针对表【t_user】的数据库操作Service实现
 * @createDate 2024-04-02 10:34:56
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
        implements UserService {

    private final RedisCacheUtils redisCacheUtils;
    private final UserMapper userMapper;
    private final IpUtils ipUtils;

    public UserServiceImpl(RedisCacheUtils redisCacheUtils, UserMapper userMapper, IpUtils ipUtils) {
        this.redisCacheUtils = redisCacheUtils;
        this.userMapper = userMapper;
        this.ipUtils = ipUtils;
    }


    /**
     * 用户注册
     * @param userRegisterRequest
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<?> register(UserRegisterRequest userRegisterRequest, HttpServletRequest request) {
        log.info("注册新用户");

        // 查询用户
        User dbUser = userMapper.selectOne(new LambdaQueryWrapper<User>().
                eq(User::getUsername, userRegisterRequest.getUserName()));

        // 判断用户是否存在
        HBAssert.isNull(dbUser, "该用户已存在");

        User user = new User();
        user.setUsername(userRegisterRequest.getUserName());

        // 用户密码加密
        user.setPassword(BCrypt.hashpw(userRegisterRequest.getPassword(), BCrypt.gensalt()));

        // 设置初始昵称
        user.setNickName(UserConstants.INIT_NICK_NAME);

        // 设置初始头像
        user.setAvatar(UserConstants.INIT_AVATAR);

        // 设置时间
        user.setCreateTime(LocalDateTime.now());
        user.setEndTime(LocalDateTime.now());

        // 保存用户
        save(user);

        // 更新用户ip和ip详细
        String ipAddr = ipUtils.getIpAddr(request);
        ipUtils.refreshIpDetailAsync(user.getId(), ipAddr, LoginConstant.USER_REGISTER);


        log.info("新用户注册完毕");

        return Result.success("用户注册成功");
    }
}




